<template>
  <div>
    <div
      class="-mt-46 h-[calc(100vh-15px)] custom-navbar-wrapper pt-46 flex flex-col"
    >
      <NormalTabs
        :tabs="CATEGORIES.map(item => ({ id: item.id, name: item.name }))"
        :active-id="activeCategoryId"
        :tab-class="tabClass"
        @update:active-id="activeCategoryId = $event"
      />
      <div
        class="c-bg-FF4A35-10 px-15 h-30 mt-5 w-full text-FF4A35 text-13 flex items-center"
      >
        失败数据三个月后自动清除
      </div>
      <div class="flex justify-between items-center pt-15 px-15">
        <div
          v-for="item in humanStatusList"
          :key="item.value"
          :class="{
            'c-linear-purple text-white': item.value === humanActiveStatus
          }"
          class="tab-item min-w-72 px-12 h-28 text-13 leading-28 text-center rounded-6 bg-F5F5F5"
          @click="changeHumanActiveStatus(item)"
        >
          {{ item.label }}
        </div>
      </div>
      <div
        ref="scrollContainer"
        class="scroll-view scroll-view--vertical hide-scrollbar flex-1"
        :style="popoverVisible ? 'overflow-y: hidden;' : ''"
      >
        <div ref="scrollContent" class="scroll-view__content">
          <!-- 视频列表 -->
          <div v-if="activeCategoryId === 'myHuman'" class="mx-15">
            <HumanListItem
              v-for="item in historyData.myHuman.records"
              :key="item.humanId"
              :item="item"
            />
          </div>

          <!-- 图片列表 -->
          <div v-if="activeCategoryId === 'timbre'" class="mx-15">
            <TimbreListItem
              v-for="item in historyData.timbre.records"
              :key="item.timbreId"
              :item="item"
              @update:popover-visible="popoverVisible = $event"
            />
          </div>

          <!-- 加载状态 -->
          <div v-if="isLoading" class="py-20 flex justify-center items-center">
            <van-loading size="24px" vertical>
              <span class="text-13 text-999 mt-10">加载中...</span>
            </van-loading>
          </div>

          <!-- 没有更多数据 -->
          <div
            v-if="
              isFinished && historyData[activeCategoryId].records.length > 0
            "
            class="py-15 text-center text-13 text-999"
          >
            <span class="inline-block px-10 py-5 rounded-full bg-gray-100"
              >没有更多数据了</span
            >
          </div>
          <!-- 空状态 -->
          <EmptyState v-if="!isLoading && historyData[activeCategoryId].records.length === 0" class="mt-50"/>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch, nextTick, onBeforeUnmount } from "vue";
import { HUMAN_IMG_STATUS_ENUM } from "@/enums";
import NormalTabs from "@/components/NormalTabs/index.vue";
import type { PageResponse } from "src/types";
import { IMG_CDN_39 } from "@/constants";
import { showToast } from "vant";
import {
  getMyHumanInfoList,
  getNoFailTimbreInfoList
} from "@/api/MyHumanHistory";
import HumanListItem from "@/views/MyHuman/HumanListItem.vue";
import TimbreListItem from "@/views/MyHuman/TimbreListItem.vue";

defineOptions({
  name: "MyHumanHistory"
});
// 提取 HUMAN_IMG_STATUS_ENUM 的值类型
type HUMAN_IMG_STATUS_ENUM =
  (typeof HUMAN_IMG_STATUS_ENUM)[keyof typeof HUMAN_IMG_STATUS_ENUM];
interface HumanStatusItem {
  value: HUMAN_IMG_STATUS_ENUM | null;
  label: string;
}
// 数字人状态
const humanStatusList: HumanStatusItem[] = [
  {
    value: null,
    label: "全部"
  },
  {
    value: HUMAN_IMG_STATUS_ENUM.SUCCESS,
    label: "已生成"
  },
  {
    value: HUMAN_IMG_STATUS_ENUM.MAKING,
    label: "生成中"
  },
  {
    value: HUMAN_IMG_STATUS_ENUM.FAIL,
    label: "生成失败"
  }
];
// 激活的数字人状态
const humanActiveStatus = ref<HUMAN_IMG_STATUS_ENUM | null>(null);
// 改变激活的数字人状态
const changeHumanActiveStatus = (humanStatusParam: HumanStatusItem) => {
  humanActiveStatus.value = humanStatusParam.value;

  // 重置当前分类的数据
  const currentCategory = activeCategoryId.value;
  historyData.value[currentCategory] = {
    current: 1,
    pages: 0,
    records: [],
    size: 24,
    total: 0
  };

  // 重置加载状态
  isFinished.value = false;

  // 重新加载数据
  loadHistoryData(false);
};

// 分类配置
const CATEGORIES = [
  { id: "myHuman", name: "数字人", api: getMyHumanInfoList },
  { id: "timbre", name: "音色", api: getNoFailTimbreInfoList }
];
const activeCategoryId = ref<string>("myHuman");

// 样式配置
const tabClass = ref({
  justifyContent: "justify-around",
  itemWidth: "w-140",
  textColor: "text-333333"
});

// 统一历史记录数据
const historyData = ref<Record<string, PageResponse<any>>>({
  myHuman: { current: 1, pages: 0, records: [], size: 24, total: 0 },
  timbre: { current: 1, pages: 0, records: [], size: 24, total: 0 }
});

// 弹窗显示状态
const popoverVisible = ref(false);

// 加载状态
const isLoading = ref(false);
const isFinished = ref(false);

// 滚动容器引用
const scrollContainer = ref<HTMLElement | null>(null);
const scrollContent = ref<HTMLElement | null>(null);

// 统一加载函数
const loadHistoryData = async (loadMore = false) => {
  if (isLoading.value) return;

  try {
    isLoading.value = true;
    const category = activeCategoryId.value;
    const currentData = historyData.value[category];

    const nextPage = loadMore ? currentData.current + 1 : 1;
    const params = {
      pageNo: nextPage,
      pageSize: 24,
      status: humanActiveStatus.value
    };

    const apiFunc = CATEGORIES.find(c => c.id === category)?.api;
    if (!apiFunc) return;

    const res = await apiFunc(params);

    historyData.value[category] = loadMore
      ? { ...res, records: [...currentData.records, ...res.records] }
      : res;

    isFinished.value = res.current >= res.pages;

    if (loadMore && res.records.length > 0) {
      showToast({
        message: `加载了 ${res.records.length} 条新记录`,
        position: "bottom"
      });
    }
  } catch (error) {
    console.error("加载失败:", error);
    showToast("加载失败，请稍后再试");
  } finally {
    isLoading.value = false;
    nextTick(() => {
      if (scrollContainer.value && scrollContent.value) {
        scrollContainer.value.addEventListener("scroll", handleScroll);
      }
    });
  }
};

// 监听分类切换
watch(activeCategoryId, newId => {
  // 移除旧分类的滚动监听
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }
  // 清空其他分类的数据
  const otherCategory = newId === "myHuman" ? "timbre" : "myHuman";
  historyData.value[otherCategory] = {
    current: 1,
    pages: 0,
    records: [],
    size: 24,
    total: 0
  };
  humanActiveStatus.value = null;
  // 加载新分类数据
  if (historyData.value[newId].records.length === 0) {
    loadHistoryData();
  }
});

// 处理滚动事件
const handleScroll = () => {
  if (
    !scrollContainer.value ||
    !scrollContent.value ||
    isLoading.value ||
    isFinished.value
  )
    return;

  const containerHeight = scrollContainer.value.clientHeight;
  const contentHeight = scrollContent.value.scrollHeight;
  const scrollTop = scrollContainer.value.scrollTop;
  const distanceToBottom = contentHeight - (scrollTop + containerHeight);

  if (distanceToBottom < 50) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
    loadHistoryData(true);
  }
};

onMounted(() => {
  // 初始加载当前分类数据
  loadHistoryData();
});

onBeforeUnmount(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }
});
</script>

<style scoped lang="less">
.tab-item:not(:last-child) {
  margin-right: 10px;
}
</style>
